package com.campus_information_portal.service.impl;

import com.campus_information_portal.dao.StudentDao;
import com.campus_information_portal.entity.MarkCondition;
import com.campus_information_portal.entity.Student;
import com.campus_information_portal.entity.StudentInfo;
import com.campus_information_portal.service.StudentService;
import com.campus_information_portal.util.DateUtil;
import com.campus_information_portal.util.Message;
import com.campus_information_portal.util.Msg;
import com.itextpdf.text.*;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.List;

/**
 * @author 20155883 万珊
 * @description 学生业务实现类
 * @project_name StudentImpl
 * @package com.campus_information_portal.service
 * @create 2018-04-19 15:48
 **/
@Service
@Transactional(rollbackFor=Exception.class)
public class StudentImpl implements StudentService {
    @Autowired
    private StudentDao studentDao;

    /**
     * @param stu_num
     * @Description 根据Student表中的学生学号查询学生个人信息
     * @author 20155883 万珊
     * @methodName queryStudentByStuNum
     * @returnType Message
     * @create 2018/4/26 8:45
     **/
    @Cacheable(value = "myCache", key = "'StudentService.queryStudentByStuNum'")
    @Override
    public Message queryStudentByStuNum(int stu_num) {
        System.out.println("*************************************************我是Student缓存方法*************************************************");

        StudentInfo student = studentDao.queryStudentByStuNum(stu_num);
        if (student != null) {
            return Message.success().add("student", student);
        }
        return Message.fail().add("0203", "查询失败");
    }

    /**
     * @param stu_num
     * @Description 查询学号是否存在
     * @author 20155880 房雁颖
     * @methodName queryStuNum
     * @returnType int
     * @create 2018/4/26 8:45
     **/
    @Override
    public Message queryStuNum(int stu_num) {
        Student student=studentDao.queryStuNum(stu_num);
        if (student!=null){
            return Message.success().add("student",student);
        }
        return Message.fail().add("0207","查询失败");
    }

    /**
     * @param student
     * @Description 增加一个学生（学号+密码）
     * @author 20155880 房雁颖
     * @methodName addStudent
     * @returnType Message
     * @create 2018/4/26 15:26
     **/
    @Override
    public Message addStudent(Student student) {
        boolean flag = studentDao.addStudent(student,student.getStuInfoId());
        if (flag==true){
            return Message.success();
        }
        return Message.fail().add("0204","增加失败");
    }

    /**
     * @param student
     * @Description 修改学生信息表（姓名，性别，身份证，出生年月，民族，电话，籍贯）
     * @author 20155880 房雁颖
     * @methodName updateStudent
     * @returnType Message
     * @create 2018/4/26 15:26
     **/
    @Override
    public Message updateStudent(Student student) {
        boolean flag = studentDao.updateStudent(student);
        if (flag==true){
            return Message.success();
        }
        return Message.fail().add("0205","更新失败");
    }

    /**
     * @param stu_num
     * @Description 删除学生信息表【警告！这是真删！无特殊情况不可调用此接口！】
     * @author 20155883 万珊
     * @methodName deleteStudent
     * @returnType Message
     * @create 2018/4/26 15:26
     **/
    @Override
    public Message deleteStudent(int stu_num) {
        boolean flag = studentDao.deleteStudent(stu_num);
        if (flag==true){
            return Message.success();
        }
        return Message.fail().add("0206","删除失败");
    }

    /**
     * @Description 查询全部学生
     * @author 20155883 万珊
     * @methodName queryStudent
     * @returnType Message
     * @create 2018/4/26 8:45
     **/
    @Override
    public Message queryStudent() {
        List<Student> studentList=studentDao.queryStudent();
        if (studentList.size()!=0){
            return Message.success().add("studentList",studentList);
        }
        return Message.fail().add("1118","查询失败");
    }

    /**
     * @Description 查询全部年级（除去重复字段）
     * @author 20155883 万珊
     * @methodName queryGrade
     * @returnType List
     * @create 2018/4/26 8:45
     **/
    @Override
    public List<String> queryGrade() {
        List<String> grade=studentDao.queryGrade();
        return grade;
    }

    /**
     * @param
     * @Description 跟据学号查学生id
     * @author 20155884 王晓阳
     * @methodName
     * @returnType
     * @create 2018/5/27 14:13
     **/
    @Override
    public Msg queryStuIdByStuNum(int stuNum) {
        Student student = studentDao.queryStuIdByStuNum(stuNum);
        if (student != null) {
            return Msg.addData(100, "student", student);
        }
        return Msg.fail();
    }

    /**
     * @param
     * @Description 根据学生id查找学生信息
     * @author 20155884 王晓阳
     * @methodName
     * @returnType
     * @create 2018/5/27 23:19
     **/
    public Msg queryStudentByStuId(int stuInfoId) {
        Student student = studentDao.queryStudentByStuId(stuInfoId);
        if (student != null) {
            return Msg.addData(100, "student", student);
        }
        return Msg.fail();
    }

    /**
     * @param
     * @Description 查找所有学生id， 学号，姓名
     * @author 20155884 王晓阳
     * @methodName
     * @returnType
     * @create 2018/5/29 20:52
     **/
    public List<MarkCondition> queryAllStudent() {
        List<MarkCondition> studentList = studentDao.queryAllStudent();
        return studentList;
    }

    /**
     * @Description 下载生成学生信息表
     * @author 20155883 万珊
     * @methodName download
     * @param
     * @returnType Message
     * @create 2018/5/21 17:27
     **/
    @Override
    public Message download(String stuNum, String stuName, String stuSex, String stuIdcardNum, String stuBirthday, String stuNation, String stuPoli, String stuPhone, String stuNativeplace, String stuGrade, String cet46Grade, String academyName) throws IOException, DocumentException {
        System.out.println("-------------------");
        System.out.println(stuNum);
        System.out.println(stuName);
        System.out.println(stuSex);
        System.out.println(stuIdcardNum);
        System.out.println(stuBirthday);
        System.out.println(stuNation);
        System.out.println(stuPoli);
        System.out.println(stuPhone);
        System.out.println(stuNativeplace);
        System.out.println(stuGrade);
        System.out.println(cet46Grade);
        System.out.println(academyName);

        // 模板路径.最终放在服务器下。远程即可访问
        java.lang.String templatePath = "D:/tj.pdf";
        // 生成的新文件路径
        //首先获取获取本机计算机名称
        // InetAddress addr = InetAddress.getLocalHost();
        //java.lang.String hostName=addr.getHostName().toString();
        //保存在指定目录上
        java.lang.String newPDFPath = "D:/"+stuName+"_天津理工大学学生基本信息表.pdf";
        //这里应该访问远程的照片，数据表应加一列图片
//        java.lang.String imagePath = "D:/tjut.JPG";

        //图片域的名字
//        java.lang.String fieldName = "img";
        PdfReader reader;
        FileOutputStream out;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        try {
//            out = new FileOutputStream(newPDFPath);// 输出流
//            reader = new PdfReader(templatePath);// 读取pdf模板
//            bos = new ByteArrayOutputStream();
//            stamper = new PdfStamper(reader, bos);
//            AcroFields form = stamper.getAcroFields();

            out = new FileOutputStream(newPDFPath);// 输出流
            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();

            //String[] str = { stuNum,"123456789", "TOP__ONE", "男", "1991-01-01", "130222111133338888", "河北省保定市" };
           /* String[] str = { stuNum,"红小", stuSex, stuIdcardNum, stuBirthday, stuNation,stuPoli,stuPhone,stuNativeplace,stuGrade,cet46Grade,academyName};
            int i = 0;
            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next().toString();
                System.out.println(name);
                form.setField(name, str[i++]);
            }
            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();*/
//            int pageNo = form.getFieldPositions(fieldName).get(0).page;
//            Rectangle signRect = form.getFieldPositions(fieldName).get(0).position;
//            float x = signRect.getLeft();
//            float y = signRect.getBottom();
            // 读图片
//            Image image = Image.getInstance(imagePath);
            // 获取操作的页面
//           PdfContentByte under = stamper.getOverContent(pageNo);
//            // 根据域的大小缩放图片
//            image.scaleToFit(signRect.getWidth(), signRect.getHeight());
//            // 添加图片
//            image.setAbsolutePosition(x, y);
//            under.addImage(image);
            //设置表单域的内容
            long dateNow=System.currentTimeMillis();
            String sR=Long.toString(dateNow);

            form.setFieldProperty("Barcode", "textfont", baseFont, null);
            form.setField("Barcode",sR);
            form.setField("stuNum",stuNum);
            form.setFieldProperty("stuName", "textfont", baseFont, null);
            form.setField("stuName",stuName);
            form.setFieldProperty("stuSex", "textfont", baseFont, null);
            form.setField("stuSex", stuSex);
            form.setFieldProperty("academyName", "textfont", baseFont, null);
            form.setField("academyName",academyName);
            form.setField("stuGrade",stuGrade);
            form.setFieldProperty("stuNation", "textfont", baseFont, null);
            form.setField("stuNation", stuNation);
            form.setFieldProperty("stuNativeplace", "textfont", baseFont, null);
            form.setField("stuNativeplace", stuNativeplace);
            form.setFieldProperty("stuPoli", "textfont", baseFont, null);
            form.setField("stuPoli",stuPoli);
            form.setField("stuBirthday",stuBirthday);
            form.setField("cet46Grade", cet46Grade);
            form.setField("stuIdcardNum",stuIdcardNum);
            form.setField("stuPhone",stuPhone);
//
//            // 如果为false那么生成的PDF文件还能编辑，一定要设为true

            stamper.setFormFlattening(true);
            stamper.close();
            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);

            copy.addPage(importPage);
            doc.close();
            reader.close();

        } catch (IOException e) {
            System.out.println(1);
        } catch (DocumentException e) {
            System.out.println(2);
        }
        return Message.success();
    }


}
